package com.tomkk.utils;

import java.sql.*;

/**
 * Created by Tomkk on 2016/5/21.
 */
public class MysqlOperation {
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    public Connection checkConn(){
        if(connection == null){
            connection = new MysqlConnector().getConnection();
            if(connection == null){
                System.out.println("数据库连接失败");
                return null;
            }
        }
        return connection;
    }
    public int update(String sql){
//        MysqlOperation.checkConn();
        int affectRows = 0;
        try {
            statement = connection.createStatement();
            affectRows = statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return affectRows;
    }
    public ResultSet query(String sql){
//        MysqlOperation.checkConn();
        try{
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            return resultSet;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public int insert(String sql){
//        MysqlOperation.checkConn();
        try{
            statement = connection.createStatement();
            return  statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
    public ResultSet login(String username, String password){
//        MysqlOperation.checkConn();
        try{
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM user WHERE username = ? AND password = ?");
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            return resultSet;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void closeDB() throws SQLException {
        if(null != resultSet){
            resultSet.close();
            resultSet = null;
        }
        if(null != statement){
            statement.close();
            statement = null;
        }
        if(null != connection){
            connection.close();
            connection = null;
        }
    }
}
